/**
 * FImageActivity.java Create on 2012-8-13     
 *      
 * Copyright (c) 2012-8-13 by yiming     
 *      
 * @author <a href="alenzhangym@hotmail.com">Yiming</a>     
 * @version 1.0 
 */

package com.yimi.image;

import android.app.Activity;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.yimi.actions.SearchListener;
import com.yimi.common.MessageType;
import com.yimi.search.AHApplication;
import com.yimi.search.SearchImageService;
import com.yimi.service.BaseImageItem;
import com.yimi.service.Entity;
import com.yimi.service.ImageEntity;
import com.yimi.ui.ViewArea;
import com.yimi.util.ImageSearchUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * TODO 功能描述
 * 
 * @author Yiming
 * @version 1.0
 */
public class FImageActivity extends Activity implements SearchListener, OnClickListener {
    private LinearLayout ll_viewArea;
    private LinearLayout.LayoutParams parm;
    private ViewArea viewArea;
    private ProgressBar progressBar;
    private BaseImageItem baseImageItem;
    private AHApplication app;
    private SearchImageService searchService;
    private Bitmap map;
    private byte[] bitmap;
    private int startPage;
    private static String TAG = "ImageActivity";
    private LinearLayout buttonLnearLayout;
    private ImageButton setwrapperButton;
    private boolean useFileCache;
    private File imageFile;
    private FileOutputStream outputStream;
    private String filePath;
    private String fileName;
    private boolean saved = false;

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        registerReceiver(bcrIntenal1, new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED));
        Bundle bund = this.getIntent().getExtras();
        if (bund != null) {
            Parcelable p = bund.getParcelable("baseImageItem");
            if (p != null) {
                baseImageItem = (BaseImageItem) p;
            }
        } else {
            this.finish();
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.setContentView(R.layout.fimageshow);
        ll_viewArea = (LinearLayout) findViewById(R.id.ll_viewArea);
        parm = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT);
        progressBar = (ProgressBar) this.findViewById(R.id.downloadprogress);
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setProgress(0);
        progressBar.setMax(100);

        buttonLnearLayout = (LinearLayout) this.findViewById(R.id.buttonContainer);
        setwrapperButton = (ImageButton) this.findViewById(R.id.setwrapper);
        setwrapperButton.setOnClickListener(this);
        app = (AHApplication) this.getApplication();
        searchService = app.getSearchImageService();

        String path = this.baseImageItem.getFileURL();
        int index = path.lastIndexOf('/');
        fileName = path.substring(index + 1);
        getMapFromFile();
        if (map != null) {
            progressBar.setVisibility(View.GONE);
            viewArea = new ViewArea(FImageActivity.this, map);
            buttonLnearLayout.setVisibility(View.VISIBLE);
        } else {
            ImageSearchUtil.clearRomFileImage();
            this.useFileCache = this.useFileCache();
            viewArea = new ViewArea(FImageActivity.this, R.drawable.temp);
            buttonLnearLayout.setVisibility(View.GONE);
            if (checkNetworkInfo()) {
                searchService.queryImageFileView(baseImageItem.getFileURL());
            } else {
                this.finish();
            }
        }// 自定义布局控件，用来初始化并存放自定义imageView
        ll_viewArea.addView(viewArea, parm);
        searchService.registerSearchListener(this);
    }

    private void getMapFromFile() {
        if (ImageSearchUtil.isPictureIsInFile(ImageSearchUtil.sdcardFilePath, fileName)) {
            try {
                map = BitmapFactory.decodeFile(ImageSearchUtil.sdcardFilePath + fileName);
            } catch (Exception e) {
                Toast.makeText(this, "内存空间不足,请关闭其他应用程序", 6000).show();
                this.finish();
            }
        } else if (ImageSearchUtil.isPictureIsInFile(ImageSearchUtil.romFilePath, fileName)) {
            try {
                map = BitmapFactory.decodeFile(ImageSearchUtil.romFilePath + fileName);
            } catch (Exception e) {
                Toast.makeText(this, "内存空间不足,请关闭其他应用程序", 6000).show();
                this.finish();
            }
        }
    }

    private boolean useFileCache() {
        boolean usesd = ImageSearchUtil.isSDCardAvailable();
        if (!usesd) {
            usesd = ImageSearchUtil.isRomAvailable();
            if (usesd) {
                this.filePath = ImageSearchUtil.romFilePath;
            } else {
                return false;
            }
        } else {
            this.filePath = ImageSearchUtil.sdcardFilePath;
        }
        return true;
    }

    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bcrIntenal1);
        progressBar.clearAnimation();
        if (map != null) {
            map.recycle();
        }
    }

    public void onBackPressed() {
        searchService.unRegisterSearchListener(this);
        searchService.cancelDownloadImage(baseImageItem.getFileURL());
        synchronized (TAG) {
            if (!saved) {
                if (outputStream != null)
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                if (imageFile != null) {
                    imageFile.delete();
                }
            }

        }
        Intent intent = new Intent(this,
                SearchActivity.class);
        this.startActivity(intent);
        this.finish();
    }

    /*
     * (non-Javadoc)
     * @see com.yimi.actions.SearchListener#onEvent(int, int,
     * com.yimi.service.Entity)
     */
    @Override
    public void onEvent(int event, int type, Entity object) {
        if (event == MessageType.EVENT_QUDERYFILEVIEWSUCCESS) {
            ImageEntity imageEntity = (ImageEntity) object;
            if (imageEntity.getFileURL().equals(this.baseImageItem.getFileURL())) {
                Log.e(TAG, " bitmap total  size is " + imageEntity.getImageSize());
                progressBar.setMax(imageEntity.getImageSize());

                Log.e(TAG, " bitmap now lenth is " + startPage);
                byte[] src = imageEntity.getImage();
                if (this.useFileCache) {
                    synchronized (TAG) {
                        if (outputStream == null) {
                            ImageSearchUtil.createFile(filePath, fileName);
                            imageFile = new File(this.filePath + this.fileName);
                            try {
                                outputStream = new FileOutputStream(imageFile);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                        Log.e(TAG, "outputStream start to write" + src.length);
                        if (src.length > 0) {
                            try {
                                outputStream.write(src);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    if (bitmap == null) {
                        try {
                            bitmap = new byte[imageEntity.getImageSize()];
                        } catch (Exception e) {
                            Toast t = Toast.makeText(this, "内存空间不足！", 6000);
                            t.show();
                            this.finish();
                        }
                    }
                    // 使用内存存储图片
                    if (src.length > 0) {
                        System.arraycopy(src, 0, bitmap, startPage, src.length);
                    }
                }
                this.startPage += imageEntity.getCurrentSize();
                progressBar.setProgress(startPage);
                if (type == MessageType.TYPE_DOWNLOAD_END) {
                    saved = true;
                    Log.e(TAG, " download over");
                    if (useFileCache) {
                        try {
                            outputStream.flush();
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        map = BitmapFactory.decodeFile(imageFile.getPath());
                    } else {
                        // 读取内存图片
                        map = BitmapFactory.decodeByteArray(bitmap, 0, bitmap.length);
                    }
                    buttonLnearLayout.setVisibility(View.VISIBLE);
                    progressBar.setVisibility(View.GONE);
                    ll_viewArea.removeView(progressBar);
                    ll_viewArea.removeView(viewArea);
                    viewArea = new ViewArea(FImageActivity.this, map);
                    ll_viewArea.addView(viewArea, parm);

                }
            }
        } else if (event == MessageType.EVENT_QUERYFILEVIEWFAILED) {
            ImageEntity imageEntity = (ImageEntity) object;
            if (imageEntity.getFileURL().equals(this.baseImageItem.getFileURL())) {
                Toast t = Toast.makeText(this, "查询失败", 6000);
                if (type == MessageType.TYPE_QUERYMAP_HTTPFAILED) {
                    t = Toast.makeText(this, "连接服务失败", 6000);
                } else if (type == MessageType.TYPE_QUEYRMAP_FAILED) {
                    t = Toast.makeText(this, "查询失败", 6000);
                } else if (type == MessageType.TYPE_QUERYMAP_TOOLARGER) {
                    t = Toast.makeText(this, "图片太大,不可下载哦", 6000);
                }
                t.show();
            }
        }

    }

    private boolean checkNetworkInfo()
    {
        ConnectivityManager conMan = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        // mobile 3G Data Network

        State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

        // 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接

        if (wifi == State.CONNECTED || wifi == State.CONNECTING)
            return true;
        Toast t = Toast.makeText(this, "请先设置无线网络，下载图片", 3000);
        t.show();
        this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
        return false;
    }

    /*
     * (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View view) {
        if (view == setwrapperButton) {
            // 设置为壁纸
            if (!setwrapperButton.isSelected()) {
                setwrapperButton.setSelected(true);
                Log.e(TAG, "setwrapperButton  click");
                WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
                try {
                    wallpaperManager.setBitmap(map);
                } catch (IOException e) {
                    Toast.makeText(this, "设置壁纸失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private BroadcastReceiver bcrIntenal1 = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "intent.getFlags()  is " + intent.getFlags());
            if (Intent.ACTION_WALLPAPER_CHANGED.equals(action) && intent.getFlags() == 0) {
                setwrapperButton.setVisibility(View.GONE);
                Toast.makeText(FImageActivity.this, "设置壁纸成功", Toast.LENGTH_SHORT).show();
            }
        }
    };
}
